import CryptoJS from 'crypto-js'
// 秘钥，必须由16位字符组成
const SECRET_KEY = 'biso.uduemc.com'

// 定义秘钥
const SECRET_KEY_MD5 = CryptoJS.enc.Utf8.parse(CryptoJS.MD5(SECRET_KEY).toString().substring(0, 16))

let base = {}

// 16进制ASCII转字符串
base.hexToString = function (hex) {
  var arr = hex.split('')
  var out = ''
  for (var i = 0; i < arr.length / 2; i++) {
    var tmp = '0x' + arr[i * 2] + arr[i * 2 + 1]
    var charValue = String.fromCharCode(tmp)
    out += charValue
  }
  return out
}

// 字符串转16进制ASCII
base.stringToHex = function (str) {
  var val = ''
  for (var i = 0; i < str.length; i++) {
    if (val === '') {
      val = str.charCodeAt(i).toString(16)
    } else {
      val += str.charCodeAt(i).toString(16)
    }
  }
  return val
}

/**
 * aes128加密
 * @param data     明文
 * @param secretKey  密钥
 * @returns {*}
 */
base.encrypt = function (content, seed) {
  let encrypted = CryptoJS.AES.encrypt(content, seed, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return this.stringToHex(encrypted.toString())
}

/**
 * aes128解密
 * @param data        密文
 * @param secretKey     密钥
 * @returns {*}
 */
base.decrypt = function (content, seed) {
  let hex = this.hexToString(content)
  let decrypt = CryptoJS.AES.decrypt(hex, seed, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return CryptoJS.enc.Utf8.stringify(decrypt).toString()
}

base.en = function (data) {
  return base.encrypt(data, SECRET_KEY_MD5)
}

base.de = function (data) {
  return base.decrypt(data, SECRET_KEY_MD5)
}

export default base
